package com.zone.vehicle.superapp.model;

import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.zone.lib.download.DownloadHelper;
import com.zone.lib.download.db.DownloadDaoUtilsStore;
import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.enums.AppStatusEnum;
import com.zone.lib.download.enums.AppTypeEnum;
import com.zone.lib.download.install.AndroidP;
import com.zone.lib.download.utils.DownloadUtil;
import com.zone.lib.download.utils.SharedPreferencesUtil;
import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.common.http.callback.ResultCallBack;
import com.zone.sdk.module.appstore.entity.AppDetailEntity;
import com.zone.sdk.module.appstore.request.AppsDetailRequest;
import com.zone.sdk_api.ApiManager;
import com.zone.vehicle.superapp.bean.AppBean;
import com.zone.vehicle.superapp.utils.JDUtil;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;

import static com.zone.sdk_api.common.Content.VIN;

/**
 * @Author: pkqlqx
 * @CreateDate: 2022/1/23 15:46
 * @Description:
 */
public class SuperAppServiceModel {

    public static void downloadApp(Context context, String code, AppStatusEnum appStatusEnum){
        if (StringUtils.isEmpty(code)){
            return;
        }
        AppsDetailRequest request = new AppsDetailRequest();
        request.setSpuId(code);
        request.setVin(SharedPreferencesUtil.getInstance(context).getSP(VIN));
        request.setUserId(SharedPreferencesUtil.getInstance(context).getUserId(context));
        ApiManager.getInstance().appsDetail(request, new ResultCallBack<Result<AppDetailEntity>>() {
            @Override
            public void onSuccess(Result<AppDetailEntity> result) {
                if (result.getResultCode().equals("200")) {
                    AppDetailEntity appEntity = result.getData();
                    if (appEntity != null && StringUtils.isNotEmpty(appEntity.getAppType()) && appEntity.getAppType().equals(AppTypeEnum.APP.getName())){
                        String userId = SharedPreferencesUtil.getInstance(context).getUserId(context);
                        DownloadUtil.downLoad(context, appStatusEnum.CODE, userId, appEntity);
                    }
                }
            }

            @Override
            public void onError(String errorCode, String message) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    public static void delete(Context context, String code){
        Log.d("val-push-message", "val-push-message delete start code="+code);
        if (StringUtils.isEmpty(code)){
            return;
        }
        Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(code);
        if (ObjectUtils.isEmpty(download)){
            return;
        }
        Log.d("val-push-message", "val-push-message delete download="+ JSON.toJSONString(download));
        if (download.getAppType().equals(AppTypeEnum.APP_LIGHT.getName())){
            JDUtil.delete(context, download.getCode(), download.getAppType());
//            appletPush(context, appBean, AppStatusEnum.LIGHT_DELETE);
        }else if (download.getAppType().equals(AppTypeEnum.APP.getName())){
            if (ObjectUtils.isNotEmpty(download)){
                if (download.getDownloadStatus() == AppStatusEnum.INSTALL_SUCCESS.CODE){
                    AndroidP.uninstall(context, download.getCode(), download.getPackageName());
                }
                DownloadHelper.getInstance().deleteTask(context, download.getCode());
                File file = new File(download.getFilePath());
                // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
                if (file.exists() && file.isFile()) {
                    file.delete();
                }
                DownloadDaoUtilsStore.getInstance().deleteByCode(code);
                Log.d("val-push-message", "val-push-message delete db="+code);
//                DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().delete(download);
            }
        }
    }

    public static void pauseDownload(Context context, String code){
        if (StringUtils.isEmpty(code)){
            return;
        }
        Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(code);
        if (ObjectUtils.isEmpty(download)){
            return;
        }
        AppDetailEntity appEntity = DownloadUtil.build(download);
        if (ObjectUtils.isEmpty(appEntity)){
            return;
        }
        DownloadUtil.downLoad(context, AppStatusEnum.DOWNLOAD_PAUSE.CODE, SharedPreferencesUtil.getInstance(context).getUserId(context), appEntity);
    }

    public static void updateApk(Context context, String code){
        if (StringUtils.isEmpty(code)){
            return;
        }
        Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(code);
        if (ObjectUtils.isEmpty(download)){
            return;
        }
        DownloadDaoUtilsStore.getInstance().deleteByCode(download.getCode());
        File delete = new File(download.getFilePath());
        if (delete.exists()){
            delete.delete();
        }

        AppBean appBean = new AppBean();
        appBean.setDownload(download);
        AppsDetailRequest request = new AppsDetailRequest();
        request.setSpuId(code);
        request.setVin(SharedPreferencesUtil.getInstance(context).getSP(VIN));
        request.setUserId(SharedPreferencesUtil.getInstance(context).getUserId(context));
        ApiManager.getInstance().appsDetail(request, new ResultCallBack<Result<AppDetailEntity>>() {
            @Override
            public void onSuccess(Result<AppDetailEntity> result) {
                if (result.getResultCode().equals("200")) {
                    AppDetailEntity appEntity = result.getData();
                    if (appEntity != null && appEntity.isApp()){
                        appBean.build(appEntity);
                        download.setLastVersion(download.getVersion());
                        download.setVersion(appEntity.getNewVersion());
                        download.setDownloadStatus(AppStatusEnum.DOWNLOAD_PREPARE.CODE);
                        DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().update(download);
                        downloadApp(context, code, AppStatusEnum.DOWNLOAD_PREPARE);
                    }
                }
            }

            @Override
            public void onError(String errorCode, String message) {
            }

            @Override
            public void onComplete() {
            }
        });
    }
}
